-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

-- Description: 定义支持的CPLD芯片组类型以及提供相关参数接口
local log = require 'mc.logging'
local chip = {}

local function get_anlu_file_id(chip_num, chip_index)
    return chip_index
end

local function get_lattice_file_id(chip_num, chip_index)
    return (chip_num + chip_index)
end

local function get_pangu_file_id(chip_num, chip_index)
    return (chip_num * 2 + chip_index)
end

local support_list = {
    -- 安路
    anlu_ef2l15 =           {id = 0x04004c37, get_file_id_func = get_anlu_file_id},
    anlu_ef2 =              {id = 0x03004c37, get_file_id_func = get_anlu_file_id},
    anlu_ef3 =              {id = 0x00008c3b, get_file_id_func = get_anlu_file_id},
    -- lattice
    lattice_ef2 =           {id = 0x012bd043, get_file_id_func = get_lattice_file_id},
    lattice_ef3 =           {id = 0x612bd043, get_file_id_func = get_lattice_file_id},
    lattice_lcmxo2_4000hc = {id = 0x012bc043, get_file_id_func = get_lattice_file_id},
    -- 紫光
    pango_ef2 =             {id = 0x0042a899, get_file_id_func = get_pangu_file_id},
    pango_ef3 =             {id = 0x0042b988, get_file_id_func = get_pangu_file_id},
    pango =                 {id = 0x0042b899, get_file_id_func = get_pangu_file_id},
}

function chip:get_cpld_upgrade_file_id(chip_id, chip_num, chip_index)
    for _, item in pairs(support_list) do
        if item.id == chip_id then
            return item.get_file_id_func(chip_num, chip_index)
        end
    end
    log:error("Invalid cpld device id %02X(%s)", chip_id, chip_index)
    return 0
end

function chip:check_pango_chip_id(chip_id)
    if support_list['pango'].id == chip_id or
        support_list['pango_ef2'].id == chip_id or
        support_list['pango_ef3'].id == chip_id then
        return true
    end
    return false
end

function chip:check_has_pango(cpld_info)
    for i = 1, cpld_info.device_count do
        local id = string.format("device%d_id", i)
        if chip:check_pango_chip_id(cpld_info[id]) then
            return true
        end
    end
    return false
end

return chip